from rest_framework import viewsets, status
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import Order, OrderDetail
from .serializers import OrderSerializer, OrderDetailSerializer, GetOrderSuperSerializer, GetOrderAllowSerializer, \
    PostOrderSuperSerializer, OrderListSerializer, OrderDetailListSerializer
from .filterBackends import OrderAllowPermissionFilterBackend
from rest_framework import permissions
from utils.decorators.auth import is_superuser, is_authenticated
from utils.decorators.responses import json_response, FlagException


class OrdersPagination(PageNumberPagination):
    page_size = 20
    page_query_param = "page"
    page_size_query_param = 'limit'

    # 最大能请求几条
    max_page_size = 100


class OrderViewSet(viewsets.mixins.CreateModelMixin,
                   viewsets.mixins.RetrieveModelMixin,
                   viewsets.mixins.ListModelMixin,
                   viewsets.GenericViewSet):
    queryset = Order.objects.all()
    serializer_class = PostOrderSuperSerializer
    pagination_class = OrdersPagination
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly,
    ]
    filter_backends = [
        OrderAllowPermissionFilterBackend,
    ]

    # def get_serializer_class(self):
    #     print('getView')
    #     if self.request.user.is_superuser:
    #         if self.request.method in permissions.SAFE_METHODS:
    #             # 超级用户并是获取
    #             return GetOrderSuperSerializer
    #         elif self.request.method == 'POST':
    #             # 超级用户并是提交
    #             return PostOrderSuperSerializer
    #     else:
    #         if self.request.method in permissions.SAFE_METHODS:
    #             # 普通用户并是获取
    #             return GetOrderAllowSerializer
    #     return GetOrderAllowSerializer
    '''
    {
  "records": [
    1,2
  ],
  "note": "已经治疗3次.",
  "user": "1",
    "type": 0,
  "orderDetail": [{
        "good": 1,
        "num": 1,
        "totalActualCharge": 60
    }, {
        "good": 8,
        "num": 2,
        "totalActualCharge": 80
    }]
}
    '''
    @is_authenticated
    @json_response
    def list(self, request, *args, **kwargs):
        query = Order.objects.filter(isDelete=False)
        if not self.request.user.is_superuser:
            query = query.filter(user__id=request.user.id)
        queryset = self.paginate_queryset(query)
        serializer = OrderListSerializer(queryset, many=True)
        return self.get_paginated_response(serializer.data).data

    @is_superuser
    @json_response
    def create(self, request, *args, **kwargs):
        # print("view")
        # print(request.data)
        serializer = PostOrderSuperSerializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return
        except Exception as e:
            return FlagException(False, 400, e.__str__())

    @is_authenticated
    @json_response
    def retrieve(self, request, *args, **kwargs):
        user_id = kwargs['pk']
        query = Order.objects.all()

        if self.request.user.is_superuser:
            if user_id:
                query = query.filter(user__id=user_id)
            else:
                query = query.filter(user__id=request.user.id)

        queryset = self.paginate_queryset(query)
        # serializer = OrderDetailListSerializer(queryset, many=True)
        # return self.get_paginated_response(serializer.data).data
        serializer = OrderListSerializer(queryset, many=True)
        return self.get_paginated_response(serializer.data).data


class OrderDetailViewSet(viewsets.ModelViewSet):
    queryset = OrderDetail.objects.all()
    serializer_class = OrderDetailSerializer
    permission_classes = [permissions.IsAdminUser]
